package com.dataStructure.Map;

import java.util.*;

/**
 * 这个map是对linerMap的优化，我们将之前MyLinerMap的一个大列表分解成多个小列表，这样的话可以减少遍历的次数，但是
 * 本质上还是线性时间，只是比线性时间 ”短了一点“
 * @param <K>
 * @param <V>
 */
public class MyBetterMap<K,V> implements Map<K,V> {


    protected List<MyLinerMap<K,V>> maps;

    public MyBetterMap(int k) {
        this.makeBetterMap(k);
    }

    protected void makeBetterMap(int k) {
        maps = new ArrayList<>(k);
        for (int i = 0 ; i < k; i++) {
            maps.add(new MyLinerMap<>());
        }
    }

    /**
     * 这个
     * @param target
     * @return
     */
    private MyLinerMap<K,V> chooseMap(Object target) {
        if (target == null) {
            return maps.get(0);
        }
        int index = Math.abs(target.hashCode() % maps.size());
        return maps.get(index);
    }

    @Override
    public int size() {
        // add up the sizes of the sub-maps
        int total = 0;
        for (MyLinerMap<K, V> map: maps) {
            total += map.size();
        }
        return total;
    }

    @Override
    public boolean isEmpty() {
        return false;
    }

    @Override
    public boolean containsKey(Object key) {
        MyLinerMap<K, V> kvMyLinerMap = this.chooseMap(key);
        V v = kvMyLinerMap.get(key);
        if (v == null) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public boolean containsValue(Object value) {
        for (MyLinerMap<K, V> map : maps) {
            if(map.containsValue(value)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public V get(Object key) {
        MyLinerMap<K, V> kvMyLinerMap = this.chooseMap(key);
        return kvMyLinerMap.get(key);
    }

    @Override
    public V put(K key, V value) {
        MyLinerMap<K, V> kvMyLinerMap = this.chooseMap(key);
        return kvMyLinerMap.put(key, value);
    }

    @Override
    public V remove(Object key) {
        return null;
    }

    @Override
    public void putAll(Map<? extends K, ? extends V> m) {

    }

    @Override
    public void clear() {

    }

    @Override
    public Set<K> keySet() {
        return null;
    }

    @Override
    public Collection<V> values() {
        return null;
    }

    @Override
    public Set<Entry<K, V>> entrySet() {
        return null;
    }
}
